package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.search.domain.dto.ItemDTO;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.enums.EsHttpHost;
import com.hmall.search.service.SearchService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class SearchServiceimpl implements SearchService {
    private final RestHighLevelClient client=
            new RestHighLevelClient(RestClient.builder(HttpHost.create(EsHttpHost.LOCALHOST.getHost()+":"+EsHttpHost.LOCALHOST.getPort())));

    @Override
    public Page<ItemDTO> getItems(ItemPageQuery query) {
        //1.创建请求对象
        SearchRequest request=new SearchRequest("items");
        //2.添加参数
        request.source().query(QueryBuilders.matchQuery("name", query.getKey()));
        request.source().query(QueryBuilders.boolQuery()
                .filter(QueryBuilders.termQuery("brand", query.getBrand()))
                .filter(QueryBuilders.termQuery("category", query.getCategory()))
                .filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()))
                .filter(QueryBuilders.termQuery("status", 1))).sort("update_time",SortOrder.DESC);
        //3.发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        Page<ItemDTO> itemDTO = parseReToPage(response, query);
        return itemDTO;
    }

    private Page<ItemDTO> parseReToPage(SearchResponse response, ItemPageQuery query) {
         SearchHits hits = response.getHits();
         SearchHit[] searchHits = hits.getHits();
         List<ItemDTO> itemDTOList = JSON.parseArray(JSON.toJSONString(searchHits), ItemDTO.class);
         Page<ItemDTO> page = Page.of(query.getPageNo(), query.getPageSize());
         page.setRecords(itemDTOList);
         page.setTotal(hits.getTotalHits().value);
         return page;
    }
}
